package com.xkw.demo.aspect;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xkw.demo.config.MyAnnotation;

/**
 * @Component,扫描该类
 * @Aspect,切面
 * @Order,切面执行顺序
 */
@Component
@Aspect
@Order(1)
public class MyAspect {
	
	/**
	 * 切点位置，定义使用注解的位置
	 */
	@Pointcut("@annotation(com.xkw.demo.config.MyAnnotation)")
	public void myAspect(){}
	
	
	/**
	 * 执行切面方法
	 * @Before,是在所拦截方法执行之前执行一段逻辑
	 * @After,是在所拦截方法执行之后执行一段逻辑
	 * @Around,是可以同时在所拦截方法的前后执行一段逻辑
	 * @param joinPoint
	 */
	@Before("myAspect()")
	public void doBeforeMyAspect(JoinPoint joinPoint) {
		// 获取request
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		//String token = request.getHeader("Authorization"); // 从 http 请求头中取出 token
		// 从切面织入点处通过反射机制获取织入点处的方法
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		if(signature != null) {
			Map<String,String[]> param = request.getParameterMap();
			// 获取切入点所在的方法
			Method method = signature.getMethod();
			// 获取操作
			MyAnnotation myLog = method.getAnnotation(MyAnnotation.class);
			String operate = myLog.operate();
			boolean isSave = myLog.isSave();
			//获取请求的类名
			String className = joinPoint.getTarget().getClass().getName();
			// 获取请求的方法名
			String methodName = method.getName();
			//获取参数
			String name = param.get("name") !=null?param.get("name")[0]:"无";
			String record = "姓名："+name+"，操作："+operate+"，存储："+isSave+"，类名："+className+"，方法名："+methodName;
			System.out.println(record);
			
		}
		
	}

	
}
